package org.learn.spring_quartz.bean;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.concurrent.atomic.AtomicReference;

@Configuration
public class WebClientConfig {
    // 用 AtomicReference 保存全局 token
    private final AtomicReference<String> globalToken = new AtomicReference<>("initial-token");

    // 提供方法动态更新 token
    public void updateToken(String token) {
        globalToken.set(token);
    }

    @Bean
    public WebClient webClient(WebClient.Builder builder) {
        return builder
                .filter((request, next) -> {
                    // 在每次请求前动态添加请求头
                    var newRequest = ClientRequest.from(request)
                            .header("Authorization", globalToken.get())
                            .build();
                    return next.exchange(newRequest);
                })
                .build();
    }
}
